package com.uam.core.service;

import java.awt.geom.Point2D;
import java.io.IOException;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uam.core.cache.PointCacheConfig;
import com.uam.core.entity.PointInfoData;
import com.uam.core.entity.uitls.GeoUtil;
import com.uam.core.lk.utils.fencebuffer.BufferBase;
import com.uam.core.scheduler.PointInfoScheduler;
import com.uam.core.scheduler.RelPointScheduler;
import com.uam.core.vo.SectorIndexVo;
import io.reactivex.Observable;
import org.elasticsearch.common.geo.builders.CoordinatesBuilder;
import org.elasticsearch.common.geo.builders.PolygonBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.GeoShapeQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.uam.core.dao.elasticsearch.ElasticsearchDao;
import com.uam.core.dao.mysql.AircraftDao;
import com.uam.core.dao.mysql.SectorStatDao;
import com.uam.core.dao.mysql.TaskDao;
import com.uam.core.entity.enums.ElasticsearchIndices;
import com.uam.core.entity.model.ElasticsearchQueryResult;
import com.uam.core.entity.model.ElasticsearchQueryResult.AreaFields;
import com.uam.core.entity.model.ElasticsearchQueryResult.CommonFields;
import com.uam.core.entity.model.ElasticsearchQueryResult.RouteComponentFields;
import com.uam.core.entity.model.SectorStatModel;
import com.uam.core.entity.model.TaskModel;
import com.uam.core.entity.model.TaskQueryResult;

import lombok.extern.slf4j.Slf4j;

import javax.swing.text.html.parser.Entity;

/**
 * 扇区管理
 *
 * @author lishf
 */
@Service
@Slf4j
public class SectorService {

	public static final int[] OPERATION_FAILURE_STATUS = new int[0];

	@Autowired
	private TaskDao taskDao = null;

	@Autowired
	private SectorStatDao sectorStatDao = null;


	@Autowired
	private ElasticsearchDao elasticsearchDao = null;




	public List<SectorIndexVo> getStatCount(){
		List<SectorIndexVo> data = new ArrayList<SectorIndexVo>(12);
		ElasticsearchQueryResult sectorResult = this.elasticsearchDao.query(QueryBuilders.matchAllQuery(), 1, 10000, new String[] { CommonFields.NAME.getName(), AreaFields.BORDER.getName() }, new String[0], ElasticsearchIndices.SECTOR_INDEX);
		List<Map<String, Object>> sectors = sectorResult.getData();
		JSONArray dataLines=new JSONArray(12);
		for(int i=0;i<sectors.size();i++){
			Map<String, Object> sector = sectors.get(i);
			JSONObject jsonObject=JSONObject.parseObject(JSONObject.toJSONString(sector.get("border")));
			JSONArray jsonArray=jsonObject.getJSONArray("coordinates");
			JSONArray jsonArray1=jsonArray.getJSONArray(0);

			JSONArray tempJSONArray=new JSONArray();
			Coordinate[] coordinates=new Coordinate[jsonArray1.size()];
			for (int j = 0; j < jsonArray1.size(); j++){
				coordinates[j]=new Coordinate(jsonArray1.getJSONArray(j).getDouble(0),jsonArray1.getJSONArray(j).getDouble(1));
				JSONArray temp=new JSONArray(4);
				temp.add(jsonArray1.getJSONArray(j).getDouble(0));
				temp.add(jsonArray1.getJSONArray(j).getDouble(1));
				tempJSONArray.add(temp);
			}

//			Polygon polygon=BufferBase.geometryFactory.createPolygon(coordinates);

			List<Point2D.Double> pointList = new ArrayList<Point2D.Double>();
			for(int j=0;j<coordinates.length;j++){
				Coordinate coordinate=coordinates[j];
				Point2D.Double t = new Point2D.Double(coordinate.x, coordinate.y);
				pointList.add(t);
			}
//			System.out.println(polygon.toText());
			SectorIndexVo sectorIndexVo=new SectorIndexVo(sector.get("name")+"",sector.get("id")+"",pointList);
			data.add(sectorIndexVo);

			SectorStatModel sectorStatModel=new SectorStatModel();
			List<String> dataList=new ArrayList<>();
			sectorStatModel.setTaskNames(dataList);
			sectorStatModel.setName(sectorIndexVo.getName());
			sectorStatModel.setId(sectorIndexVo.getId());
			PointInfoScheduler.sectorStatModelMap.put(sectorIndexVo.getId(),sectorStatModel);

			JSONObject jsonObject1=new JSONObject();
			jsonObject1.put("lnglat",tempJSONArray);
			dataLines.add(jsonObject1);
		}
		PointInfoScheduler.dataSectorIndex=data;
		return data;
	}

	public void checkSectorStat(Integer takId, PointInfoData pointInfoData1) {
		Point2D.Double poin2D = new Point2D.Double(pointInfoData1.getLon(), pointInfoData1.getLat());
		int row=PointInfoScheduler.dataSectorIndex.size();
		delete(takId+"");
		boolean flagOut=false;
		for(int i=0;i<row;i++){
			SectorIndexVo sectorIndexVo=PointInfoScheduler.dataSectorIndex.get(i);

			List<Point2D.Double> pointList =sectorIndexVo.getPointList();
			boolean flag= GeoUtil.isInPolygon(poin2D,pointList );
			if(flag){
				flagOut=true;
				SectorStatModel sectorStatModel=PointInfoScheduler.sectorStatModelMap.get(sectorIndexVo.getId());
				if(sectorStatModel == null){
					sectorStatModel=new SectorStatModel();
					List<String> dataList=new ArrayList<>();
					dataList.add(pointInfoData1.getTaskName());
					sectorStatModel.setTaskNames(dataList);
					sectorStatModel.setName(takId+"");
					sectorStatModel.setId(sectorIndexVo.getId());
					PointInfoScheduler.sectorStatModelMap.put(sectorIndexVo.getId(),sectorStatModel);
					return;
				}
				sectorStatModel.getTaskNames().add(pointInfoData1.getTaskName());
				PointInfoScheduler.sectorStatModelMap.put(sectorIndexVo.getId(),sectorStatModel);
				break;
			}

		}
		if(!flagOut){
			System.out.println("未找到 " + takId + "  " + JSONObject.toJSONString(pointInfoData1));
		}
	}

	public void delete(String taskId){
		Map<String, SectorStatModel> sectorStatModelMap =PointInfoScheduler.sectorStatModelMap;
		for(Map.Entry<String, SectorStatModel> modelEntity:sectorStatModelMap.entrySet()){
			if(modelEntity.getValue().getTaskNames() !=null) {
				modelEntity.getValue().getTaskNames().remove(taskId);
			}
		}
	}
	@Autowired
	private PointCacheConfig pointCacheConfig;
	public void saveSectorStat() {

		Set<Integer> takIds = pointCacheConfig.getAll().asMap().keySet();
		for (Integer takId : takIds) {
			long nowTime = System.currentTimeMillis();
			//当前任务
			Map<String, PointInfoData> dataMap = pointCacheConfig.get(takId);
			if (dataMap == null || dataMap.size() == 0) {
				continue;
			}
			Long sTime=0L;
			Long eTime=0L;
			PointInfoData ePointTemp=null;
			List<PointInfoData> pointInfoData = new ArrayList<>(dataMap.values());
			int rowIndex=pointInfoData.size();
			PointInfoData data=null;
			boolean flag=false;
			for(int i=0;i<rowIndex-1;i++){
				int sIndexTemp=i;
				int eIndexTemp=i+1;
				PointInfoData sPointTemp= pointInfoData.get(sIndexTemp);
				ePointTemp= pointInfoData.get(eIndexTemp);
				sTime=sPointTemp.getTime();
				eTime=ePointTemp.getTime();
				if(nowTime == sTime ){
					data=sPointTemp;
					break;
				}
				if(nowTime == eTime ){
					data=ePointTemp;
					break;
				}

				if(nowTime>sTime && nowTime<eTime){
					data=sPointTemp;
					break;
				}

			}

			if(data !=null){
				checkSectorStat(takId, data);
				continue;
			}
			System.out.println("区域判断没有找到时间");
			//默认最后一个
			checkSectorStat( takId,ePointTemp);
		}

		for(Map.Entry<String, SectorStatModel> set:PointInfoScheduler.sectorStatModelMap.entrySet()){
			SectorStatModel sectorStatModel=set.getValue();
			sectorStatModel.setAircraftNames(JSONArray.toJSONString(sectorStatModel.getTaskNames()));
			sectorStatModel.setCapacity(sectorStatModel.getTaskNames().size());
			sectorStatModel.setName(sectorStatModel.getName());
			sectorStatModel.setId(set.getKey());
			sectorStatModel.setNum(sectorStatModel.getTaskNames().size());
			sectorStatDao.updateSectorStat(sectorStatModel);

			sectorStatModel.setNum(0);
			sectorStatModel.setAircraftNames("[]");
			sectorStatModel.setCapacity(0);
			sectorStatModel.setTaskNames(new ArrayList<>());
		}

	}
}
